package com.example.administrator.text;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import entity.Account;
import util.BitmapUtil;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.QrcodeDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

/**
 * 绑定账号页
 */
public class WeBinDingAccountActivity extends BaseActivity {
    public static final String PACKAGE = "PACKAGE";                //时间
    public static final String PAUTHORIZATION = "PAUTHORIZATION";//免费类型标示
    public static final String BINDING = "BINDING";             //上网方式的显示
    public static final String TYPR = "TYPR";                  //标识哪里调用的
    public static final int REQUSET = 1;
    public static final int APPTIME = 2;
    private int mBindingareaid,mAreaiden; //可绑定区域ID,areaiden
    private String mPhone,mAassword; //账号和密码
    private String mToken,mId;
    private String mType,mWBDAABanding,mPauthorizationString;
    private UploadDialog mUploadDialog;
    private QrcodeDialog mQrcodeDialog;
    private String url;
    private List<Account.AreaInfoBean> mAreaInfoBeen;
    private boolean mJuderShow = true;

    @Bind(R.id.text_name_account)            TextView mTVName;            //账户名字
    @Bind(R.id.image_account)                ImageView mIVaccount;       //账号所对应的图标
    @Bind(R.id.text_dinbingaccount_hint)     TextView mTextViewHint;    //提示信息
    @Bind(R.id.edit_bindingphonet_wewifi)    EditText mETPhone;       //账号
    @Bind(R.id.edit_bindingphonet_password)  EditText mETPassword;   //密码
    @Bind(R.id.frame_dinding)                FrameLayout mFrameLayout;
    @Bind(R.id.image_bindingphonet_password) ImageView mImageView;
    @Bind(R.id.tv_firstfree)                 TextView mTViewFirstfree;                //免费时长
    @Bind(R.id.tv_string)                    TextView mTViewHint;                    //提示
    @Bind(R.id.text_dinbing)                 TextView mTViewDin;                    //提示
    @Bind(R.id.relative_webinDing)           RelativeLayout mRelativeLayout;
    @Bind(R.id.linear_package)               LinearLayout mLLayoutPackage;        //选择套餐
    @Bind(R.id.linear_authorization)         LinearLayout mLLayoutautHorization; //授权上网
    @Bind(R.id.linear_firstfree)             LinearLayout mLLayoutFirstfree;    //免费时长
    @Bind(R.id.linear_appointment)           LinearLayout mLLayoutAppointment; //预约联网
    @Bind(R.id.linear_deposit)               LinearLayout mLLayoutDeposit;    //交押金

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dinbing_account);
        ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    /**
     * 绑定
     */
    @OnClick(R.id.tv_webanding) void weDanDing(){
       if(NetUtils.getInstance(this).checkNetWork()){
           if (getjumpBanDing()) {getBanDingBaDa();}

       }else {super.getToast(getString(R.string.no_network));}
    }

    /**
     * 选择账户类型
     */
    @OnClick(R.id.image_account_account) void account1(){JumpActivityUtils.getInstance().jumAccountList(this);}

    /**
     * 选择套餐
     */
    @OnClick(R.id.tv_package) void getPackage(){
        String wevVip = (int) SharedPreferencesUtils.getParam(WeBinDingAccountActivity.this, HomeUtil.mVIPCombonum,1)+"";
        String  pattern = "";
        if(StringUtil.getStringUtilNew().getDepositPackageState(this)){
            int  pattern1 =  StringUtil.getStringUtilNew().getLookForPackage(this);
            if(pattern1 == 0){
                Toast.makeText(this,"没有找到合适的模式，请重新登录",Toast.LENGTH_SHORT).show();
                return;
            }
            pattern = pattern1+"";
        }
        LogUtil.eE("url",".....pattern......."+pattern);
        String url = Url.mATIAIRIP +Url.getUrlNew().vipdePosit+"?userid="+mId+"&vipid="+wevVip+"&pattern="+pattern;
        JumpActivityUtils.getInstance().jumpWebView(this,url,"套餐购买");

    }

    /**
     * 免费时间
     */
    @OnClick(R.id.linear_firstfree) void getFirstFree(){
                   getFirsFreeNet();
    }

    /**
     * 授权上网
     */
    @OnClick(R.id.tv_authorization) void authorization(){
        mQrcodeDialog = new QrcodeDialog(this,1);
        mQrcodeDialog.show();
    }

    /**
     * 预约联网
     */
    @OnClick(R.id.linear_appointment)
    void appointment(){
        JumpActivityUtils.getInstance().jumpAppointTime(this,"","");
    }

    /**
     * 选择账户类型
     */
    @OnClick(R.id.text_name_account) void account2(){JumpActivityUtils.getInstance().jumAccountList(this);}

    /**
     * 显示 或 不显示密码
     */
    @OnClick(R.id.image_bindingphonet_password) void binDingPhonetDhowPsw(){
        //第一次点击
        if(mJuderShow){
            mJuderShow = false;
            mETPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);//密码可见
            mImageView.setImageResource(R.mipmap.eye_true);
            //第二次点击
        }else{
            mJuderShow = true;
            mImageView.setImageResource(R.mipmap.eye_false);
            mETPassword.setInputType(0x00000081);//密码可不见
        }

        mETPassword.setText(mAassword);
        mETPassword.setSelection(mAassword.length());
    }

    /**
     * 押金
     */
    @OnClick(R.id.linear_deposit) void deposit(){

        String wevVip = (int) SharedPreferencesUtils.getParam(WeBinDingAccountActivity.this, HomeUtil.mVIPCombonum,1)+"";
        String  pattern = "";
        if(StringUtil.getStringUtilNew().getDepositPackageState(this)){
            int  pattern1 =  StringUtil.getStringUtilNew().getLookForDeposit(this);
            if(pattern1 == 0){
                Toast.makeText(this,"没有找到合适的模式，请重新登录",Toast.LENGTH_SHORT).show();
                return;
            }
            pattern = pattern1+"";
        }
        LogUtil.eE("url",".....pattern......."+pattern);
        JumpActivityUtils.getInstance().jumpWebView(this,Url.mATIAIRIP + Url.getUrlNew().vipdePosit+"?userid="+mId+"&vipid="+wevVip+"&pattern="+pattern+"&appType=1","会员购买");
    }

    /**
     * 返回键
     */
    @OnClick(R.id.image_dinbing_account)
    void dinbingAccount(){finish();}

    /**
     * 初始化
     */
    private void init() {
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        mId = (String)SharedPreferencesUtils.getParam(WeBinDingAccountActivity.this, HomeUtil.mUseridDB, "");
        mToken = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB, "");
        String stringJson = getIntent().getStringExtra(WeBinDingAccountActivity.BINDING);
        mType = getIntent().getStringExtra(WeBinDingAccountActivity.TYPR);
        LogUtil.eE("WEBIN","  "+stringJson);
        if(mType.equals("HOME")){
            try {
                mWBDAABanding = "HOME";
                JSONObject jsonObject = new JSONObject(stringJson);
                int bandingHimt = jsonObject.getInt("bandingHimt");
                if(bandingHimt == 1){
                    mRelativeLayout.setVisibility(View.VISIBLE);
                    mTViewHint.setVisibility(View.VISIBLE);
                }
                int erweimaHimt = jsonObject.getInt("erweimaHimt");
                if(erweimaHimt == 1){
                    mLLayoutautHorization.setVisibility(View.VISIBLE);
                }
                JSONObject jsonObject1 = jsonObject.getJSONObject("firstfreeHimt");
                if(jsonObject1.getInt("firstfree") == 1){
                    mLLayoutFirstfree.setVisibility(View.VISIBLE);
                    String packageUrl = jsonObject1.getString("freetime");
                    mPauthorizationString = jsonObject1.getString("areaiden");
                    if(Double.parseDouble(packageUrl) > 1){
                        mTViewFirstfree.setText("游客 免费使用"+packageUrl+"小时");
                    }else {
                        mTViewFirstfree.setText("游客 免费使用"+Double.parseDouble(packageUrl)*60+"分钟");
                    }
                }

                if(jsonObject.getInt("comboHimt") == 1){
                    mLLayoutPackage.setVisibility(View.VISIBLE);
                }
                if(jsonObject.getInt("vipHimt") == 1){
                    mLLayoutDeposit.setVisibility(View.VISIBLE);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }else if(mType.equals("WiFi")){
            ArrayList list = (ArrayList) SharedPreferencesUtils.getParam(this,HomeUtil.mAppPatternArray,"list");
            for (int i = 0; i <list.size(); i++) {
                int pattern = (int) list.get(i);
                if(StringUtil.getStringUtilNew().judgeUIType(pattern) == 1){
                    mLLayoutDeposit.setVisibility(View.VISIBLE);
                }else if(StringUtil.getStringUtilNew().judgeUIType(pattern) == 2){
                    mLLayoutPackage.setVisibility(View.VISIBLE);
                }else if(StringUtil.getStringUtilNew().judgeUIType(pattern) == 4){
                    mRelativeLayout.setVisibility(View.VISIBLE);
                    mTViewHint.setVisibility(View.VISIBLE);
                }
            }
        }else {
            mWBDAABanding = "";
            mTViewHint.setVisibility(View.GONE);
            mRelativeLayout.setVisibility(View.VISIBLE);
        }

        mETPassword.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAassword = s.toString();
            }

            @Override public void afterTextChanged(Editable s) {}});

         initData();
    }

    private boolean getjumpBanDing(){
        mPhone = mETPhone.getText().toString().trim();
        mAassword = mETPassword.getText().toString().trim();

        if(mPhone.length() == 0 || mAassword.length() == 0){
            super.getToast("账号或者密码为空");
            return false;
        }

        if(mTVName.getText().equals("")){
            super.getToast("请选择账户");
            return false;
        }
        if(mAassword.contains("（")|| mAassword.contains("）")){
            mAassword = mAassword.replace("（", "(");
            mAassword = mAassword.replace("）", ")");
        }
        LogUtil.eE("",mAassword);
        return true;
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.eE("","onActivityResult");
        if(requestCode == WeBinDingAccountActivity.REQUSET && resultCode == RESULT_OK){
            mBindingareaid = data.getIntExtra(AccountListActivity.AREAID,3);
            mAreaiden = data.getIntExtra(AccountListActivity.AREIDEN,3);
            mTVName.setText(data.getStringExtra(AccountListActivity.AREANAME));
            String pic = data.getStringExtra(AccountListActivity.AREAPIC);
            String pwdhint = data.getStringExtra(AccountListActivity.PWSNAME);
            String accounanme = data.getStringExtra(AccountListActivity.ACCOUNANME);

            if(accounanme !=null &&! accounanme.equals("")){
                mETPhone.setHint(accounanme);
            }
            if(pwdhint !=null &&! pwdhint.equals("")){
                mETPassword.setHint(pwdhint);
            }
            BitmapUtil.newBitmap().showBitmap(this,pic,mIVaccount,R.mipmap.homepage_icon,null);
        }else if(requestCode == WeBinDingAccountActivity.APPTIME && resultCode == RESULT_OK){
            finish();
        }

    }

    private void getBanDingBaDa(){
        mMap = new HashMap<>();
        mUploadDialog = new UploadDialog(this,"绑定中");
        mUploadDialog.show();
        mMap.put("account",mPhone);
        mMap.put("accountPwd",mAassword);              mMap.put("userid",mId);
        mMap.put("bindingareaid",mBindingareaid);      mMap.put("areaiden",mAreaiden);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngBinding_addBinding,stringJson,mToken,mId,time);
        Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.mStirngBinding_addBinding,stirngSign,time);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        }
        LogUtil.eE("fwq","  "+url);
        getLogger().info("getBanDingBaDa()-绑定--->fwq--"+url+"stirngSign--"+stirngSign+"...NF_callid..."+map.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    getLogger().info("getBanDingBaDa()--->onSuccess()--->String--"+response);
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    LogUtil.eE("",response);
                    mUploadDialog.dismiss();
                    if(code.equals("1")){
                        if(!mWBDAABanding.equals("")){
                            getToast("绑定成功,再次点击上网，即可联网");
                        }else {
                            getToast("绑定成功");
                            if(mType.equals("ACCOUNT")){sendBroadcast(new Intent(WeWiFiAccountActivity.mAction));}
                        }
                        finish();
                    }else if(code.equals("0")){
                        if(jsonObject.getInt("reason") == 1){
                            Toast.makeText(WeBinDingAccountActivity.this,"账号或密码错误",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(WeBinDingAccountActivity.this,"绑定失败",Toast.LENGTH_SHORT).show();
                        }
                    }else if (code.equals("-2")) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(WeBinDingAccountActivity.this);
                        crowdRetunDialog.show();
                    }else {Toast.makeText(WeBinDingAccountActivity.this, getString(R.string.FWQ), Toast.LENGTH_SHORT).show();}

                } catch (JSONException e) {e.printStackTrace();}
            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(WeBinDingAccountActivity.this, error.toString());}
        });
    }

    private void initData() {
        String stringJson ="{}"; //参数包
        mUploadDialog = new UploadDialog(this,"加载中");
        mUploadDialog.show();
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        mToken = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB, "");
        mId = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mUseridDB,"");
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngBinding_areaList,stringJson,mToken,mId,time);
        Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.mStirngBinding_areaList,stirngSign,time);
        if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mFWQ,"");
        }
        LogUtil.eE("fwq","  "+url);
        GreenTreeNetworkUtil.getInstance().doPost(this,url,1,map, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                Gson gson = new Gson();
                LogUtil.eE("JSON","initData"+response);
                mUploadDialog.dismiss();
                Account account = gson.fromJson(response,Account.class);
                if(account.getCode() == 1){
                    mAreaInfoBeen = account.getAreaInfo();
                    int projectid = MyApplication.getApp().getSiteAreaid();
                    for (int i = 0; i <mAreaInfoBeen.size() ; i++) {
                        if( mAreaInfoBeen.get(i).getBindingareaid() == projectid){
                            mBindingareaid = mAreaInfoBeen.get(i).getBindingareaid();
                            mAreaiden = mAreaInfoBeen.get(i).getAreaiden();
                            mTVName.setText(mAreaInfoBeen.get(i).getAreaName());
                            mAreaInfoBeen.get(i).getAccountName();

                            if(mAreaInfoBeen.get(i).getAccountName() !=null &&!mAreaInfoBeen.get(i).getAccountName().equals("")){
                                mETPhone.setHint(mAreaInfoBeen.get(i).getAccountName());
                            }
                            if(mAreaInfoBeen.get(i).getPwdName() !=null&&!mAreaInfoBeen.get(i).getPwdName().equals("")){
                                mETPassword.setHint(mAreaInfoBeen.get(i).getPwdName());
                            }

                            BitmapUtil.newBitmap().showBitmap(WeBinDingAccountActivity.this,mAreaInfoBeen.get(i).getAreaPic(),mIVaccount,R.mipmap.homepage_icon,null);

                        }

                    }

                }else if(account.getCode() ==-2){
                    CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(WeBinDingAccountActivity.this);
                    crowdRetunDialog.show();
                }

            }

            @Override public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
            }
        });
    }

    @Override protected void onDestroy() {
        super.onDestroy();

        if(mMap !=null){ mMap.clear();}

        if(mUploadDialog !=null){mUploadDialog.dismiss();}

        if(mQrcodeDialog !=null){mQrcodeDialog.dismiss();}

        if(mAreaInfoBeen !=null){mAreaInfoBeen.clear();}

        EventBus.getDefault().unregister(this);
    }

    /*** 订阅事件FirstEvent*/
    @Subscribe
    public void onEventMainThread(final String string){
        LogUtil.eE("","onEventMainThread......."+string);
        if(string !=null && !string.equals("")){
            if(string.equals("vip")){
                   finish();
            }
        }
    }

    /**
     * 免费上网
     */
    private void getFirsFreeNet() {
        final Handler handler = new Handler();
        mUploadDialog = new UploadDialog(this,"联网中");
        mUploadDialog.show();
        HashMap<String, Object> map = new HashMap<>();
        map.put("ip", getInformation.getNewGetInformation(this).getI_IP());
        map.put("userid",mId);
        map.put("mac",getInformation.getNewGetInformation(this).getIMAC());
        map.put("areaiden",Integer.parseInt(mPauthorizationString));
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngNetwork_timingNet,stringJson,mToken,mId,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mId,Url.mStirngNetwork_timingNet,stirngSign,time);
        getLogger().info("getFirsFreeNet()-免费联网--->fwq--"+MyApplication.getApp().getFWQString()+"stirngSign--"+stirngSign+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.getApp().getFWQString(),1,map1, new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    getLogger().info("getFirsFreeNet()-response（）--->String--"+response);
                    mUploadDialog.dismiss();
                    JSONObject json = new JSONObject(response);
                    if(json.getInt("code") == 1){
                           if(json.getInt("connect") == 1){

                            final RetunDialog retunDialog = new RetunDialog(WeBinDingAccountActivity.this,"",3,true);
                             retunDialog.show();
                             handler.postDelayed(new Runnable() {
                             @Override public void run() {
                                 retunDialog.dismiss();
                                /* Intent intent = new Intent(HomeActivity.mAction);
                                 intent.putExtra("wifi","wifiok");
                                 sendBroadcast(intent);*/
                                 finish();
                              }
                            },1000);
                           }else {
                               final RetunDialog retunDialog = new RetunDialog(WeBinDingAccountActivity.this,"",4,true);
                               retunDialog.show();
                           }
                    }else {
                        getToast(getString(R.string.FWQ));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(WeBinDingAccountActivity.this,error.toString());
            }
        });
    }

}
